package org.gruposp2p.proyectokarma.gwt.client.ui;

import org.gruposp2p.proyectokarma.gwt.client.MainEntryPoint;
import org.gruposp2p.proyectokarma.gwt.client.domain.Peer;
import com.google.gwt.core.client.GWT;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.event.dom.client.KeyCodes;
import com.google.gwt.event.dom.client.KeyDownEvent;
import com.google.gwt.event.dom.client.KeyDownHandler;
import com.google.gwt.http.client.Request;
import com.google.gwt.http.client.RequestCallback;
import com.google.gwt.http.client.Response;
import com.google.gwt.resources.client.CssResource;
import com.google.gwt.uibinder.client.UiBinder;
import com.google.gwt.uibinder.client.UiField;
import com.google.gwt.uibinder.client.UiHandler;
import com.google.gwt.user.client.Window;
import com.google.gwt.user.client.ui.Button;
import com.google.gwt.user.client.ui.DialogBox;
import com.google.gwt.user.client.ui.Label;
import com.google.gwt.user.client.ui.TextBox;
import com.google.gwt.user.client.ui.VerticalPanel;
import com.google.gwt.user.client.ui.Widget;
import org.gruposp2p.proyectokarma.gwt.client.json.DomainToJSON;
import org.gruposp2p.proyectokarma.gwt.client.util.RequestHelper;
import org.gruposp2p.proyectokarma.gwt.client.util.ServerPaths;
import org.gruposp2p.proyectokarma.gwt.client.util.Validator;
import com.google.gwt.json.client.JSONObject;
import com.allen_sauer.gwt.log.client.Log;

public class ForgotPasswordDialog {
	
    interface Style extends CssResource {
        String errorTextBox();
        String textBox();
    }
    
    @UiField DialogBox dialogBox;
    @UiField Style style;
    @UiField VerticalPanel mainPanel;
    @UiField VerticalPanel messagePanel;
    @UiField Label messageLabel;
    @UiField Button acceptButton;
    @UiField Button cancelButton;
    @UiField TextBox emailTextBox;


    private static ForgotPasswordDialogUiBinder uiBinder = GWT
                    .create(ForgotPasswordDialogUiBinder.class);

    interface ForgotPasswordDialogUiBinder extends
            UiBinder<Widget, ForgotPasswordDialog> { }

    public ForgotPasswordDialog() {
        uiBinder.createAndBindUi(this);
        acceptButton.setStylePrimaryName("acceptButton");
        cancelButton.setStylePrimaryName("cancelButton");
        messagePanel.setVisible(false);
        SubmitHandler sh = new SubmitHandler();
        emailTextBox.addKeyDownHandler(sh);
    }

    public void show() {
        dialogBox.center();
        dialogBox.show();
    }
    
    @UiHandler("acceptButton")
    void handleAcceptButton(ClickEvent e) {
		if (!isValidForm()) return;
		dialogBox.setVisible(false);
		dialogBox.hide();
		Peer peer = new Peer ();
		peer.setEmail(emailTextBox.getText());
		JSONObject JSONPeer = DomainToJSON.getPeer(peer);
		acceptButton.setEnabled(false);
		RequestHelper.doPut(ServerPaths.getForgotPasswordPath(), 
				JSONPeer.toString(), new ServerRequestCallback());
    }
    
    @UiHandler("cancelButton")
    void handleCancelButton(ClickEvent e) {
    	dialogBox.hide();
    }
	
	private boolean isValidForm() {
		if (Validator.isTextBoxEmpty(emailTextBox)) {
			setMessage(MainEntryPoint.INSTANCE.constants.emptyFieldException());
			emailTextBox.setStyleName(style.errorTextBox(), true);
			return false;
		} else {
			emailTextBox.setStyleName(style.errorTextBox(), false);
		}
		if (!Validator.isValidEmail(emailTextBox.getText())) {
			setMessage(MainEntryPoint.INSTANCE.constants.emailException());
			emailTextBox.setStyleName(style.errorTextBox(), true);
			return false;
		} else {
			emailTextBox.setStyleName(style.errorTextBox(), false);
		}
		return true;
	}
	
	private void setMessage (String message) {
    	messageLabel.setText(message);
    	messagePanel.setVisible(true);
	}
	
    private class ServerRequestCallback implements RequestCallback {

        @Override
    	public void onError(Request request, Throwable exception) {
        	new ErrorDialog().show("Exception", exception.getMessage());
        	acceptButton.setEnabled(true);
    	}

        @Override
    	public void onResponseReceived(Request request, Response response) {
			Log.debug("StatusCode: " + response.getStatusCode() + 
					", Response Text: " + response.getText());
    		if (response.getStatusCode() == Response.SC_OK || 
    				response.getStatusCode() == Response.SC_NOT_FOUND) {
    			Window.alert(response.getText());
    		} else {
    			new ErrorDialog().show("ERROR", "Error (" + response.getStatusCode() + "," 
    					+ response.getStatusText() + ")]");
    		}
    		acceptButton.setEnabled(true);
    	}

    }
    
    private class SubmitHandler implements KeyDownHandler {
		@Override
		public void onKeyDown(KeyDownEvent event) {
			if (KeyCodes.KEY_ENTER == event.getNativeKeyCode()) {
				acceptButton.click();
			}		
		}
	}
    
}